﻿namespace Sharemarker.DataAccess.Implement
{
    using System;
    using System.Collections.Generic;
    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;

    using Sharemarker.Common.DataAccess;

    using log4net;

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class AbsRepository<T> : IRepository<T>
        where T : class
    {
        #region Static Fields

        /// <summary>
        /// 
        /// </summary>
        private static readonly ILog Logger = LogManager.GetLogger(typeof(AbsRepository<T>));

        #endregion

        #region Fields

        /// <summary>
        /// 
        /// </summary>
        protected IUnitOfWork<DataContext> UnitOfWork;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="AbsRepository{T}" /> class.
        /// </summary>
        /// <param name="unitOfWork">The unit of work ma manager manager manager.</param>
        protected AbsRepository(IUnitOfWork<DataContext> unitOfWork)
        {
            this.UnitOfWork = unitOfWork;
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// Deletes the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        public void Delete(T entity)
        {
            if (entity == null)
            {
                throw new InvalidOperationException("Cannot delete null entity");
            }

            this.ExecuteDbAction(
                ofWork =>
                    {
                        Table<T> table = ofWork.GetDB().GetTable<T>();
                        this.TrytoReattache(table, entity);
                        table.DeleteOnSubmit(entity);
                        return entity;
                    });
        }

        /// <summary>
        /// Deletes the specified entities.
        /// </summary>
        /// <param name="entities">The entities.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        public void Delete(IEnumerable<T> entities)
        {
            List<T> enumerable = entities as List<T> ?? entities.ToList();
            if (enumerable.Count == 0)
            {
                return;
            }

            this.ExecuteDbAction(
                ofWork =>
                    {
                        Table<T> table = ofWork.GetDB().GetTable<T>();
                        table.DeleteAllOnSubmit(enumerable);
                        return enumerable;
                    });
        }

        /// <summary>
        /// Finds the specified where.
        /// </summary>
        /// <param name="where">The where.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public IEnumerable<T> Find(Expression<Func<T, bool>> @where)
        {
            return null;
        }

        /// <summary>
        /// Gets all.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public IEnumerable<T> GetAll()
        {
            return this.ExecuteDbAction(ofWork => ofWork.GetDB().GetTable<T>().ToList());
        }

        /// <summary>
        /// Inserts the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public T Insert(T entity)
        {
            if (entity == null)
            {
                throw new InvalidOperationException("Cannot insert null entity");
            }

            return this.ExecuteDbAction(
                ofWork =>
                    {
                        Table<T> table = ofWork.GetDB().GetTable<T>();
                        table.InsertOnSubmit(entity);
                        return entity;
                    });
        }

        /// <summary>
        /// Inserts the specified entities.
        /// </summary>
        /// <param name="entities">The entities.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public IEnumerable<T> Insert(IEnumerable<T> entities)
        {
            List<T> enumerable = entities as List<T> ?? entities.ToList();
            if (enumerable.Count == 0)
            {
                return new List<T>();
            }

            return this.ExecuteDbAction(
                ofWork =>
                    {
                        Table<T> table = ofWork.GetDB().GetTable<T>();
                        table.InsertAllOnSubmit(enumerable);
                        return enumerable;
                    });
        }

        /// <summary>
        /// Updates the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public T Update(T entity)
        {
            if (entity == null)
            {
                throw new InvalidOperationException("Cannot update null entity");
            }

            return this.ExecuteDbAction(
                ofWork =>
                    {
                        DataContext dataContext = ofWork.GetDB();
                        Table<T> table = dataContext.GetTable<T>();
                        this.TrytoReattache(table, entity);
                        return entity;
                    });
        }

        #endregion

        #region Methods

        /// <summary>
        /// The execute load data.
        /// </summary>
        /// <param name="action">
        /// The action.
        /// </param>
        /// <typeparam name="TR">
        /// The type of return object
        /// </typeparam>
        /// <returns>
        /// The TR.
        /// </returns>
        protected TR ExecuteDbAction<TR>(Func<IUnitOfWork<DataContext>, TR> action)
        {
            if (action == null)
            {
                return default(TR);
            }

            using (this.UnitOfWork)
            {
                return action(this.UnitOfWork);
            }
        }

        /// <summary>
        /// The generic detach.
        /// </summary>
        /// <param name="entity">
        /// The entity.
        /// </param>
        protected void GenericDetach(T entity)
        {
            foreach (PropertyInfo pi in entity.GetType().GetProperties())
            {
                if (pi.GetCustomAttributes(typeof(AssociationAttribute), false).Length > 0)
                {
                    // Property is associated to another entity
                    Type propType = pi.PropertyType;

                    // Invoke Empty contructor (set to default value)
                    ConstructorInfo ci = propType.GetConstructor(new Type[0]);
                    pi.SetValue(entity, ci.Invoke(null), null);
                }
            }
        }

        /// <summary>
        /// Gets the get table.
        /// </summary>
        /// <returns>Return table</returns>
        protected virtual ITable<T> GetTable()
        {
            return this.UnitOfWork.GetDB().GetTable<T>();
        }

        /// <summary>
        /// The tryto reattache.
        /// </summary>
        /// <param name="table">
        /// The table.
        /// </param>
        /// <param name="entity">
        /// The entity.
        /// </param>
        protected void TrytoReattache(ITable<T> table, T entity)
        {
            var tableType = table as Table<T>;
            if (tableType == null)
            {
                throw new InvalidOperationException("Null Linq Sql table");
            }

            try
            {
                if (tableType.GetOriginalEntityState(entity) == null)
                {
                    this.GenericDetach(entity);
                    table.Attach(entity);
                }
            }
            catch (Exception ex)
            {
                // TODO: apply log4net
            }
        }

        /// <summary>
        /// The get property value.
        /// </summary>
        /// <param name="o">
        /// The o.
        /// </param>
        /// <returns>
        /// The System.Object.
        /// </returns>
        private object GetPropertyValue(object o)
        {
            return o ?? DBNull.Value;
        }

        #endregion
    }
}